package cc.buttfu.thingbento;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import cc.buttfu.thingbento.R;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

/**
 * @author dislink.now
 * 
 * Screen allowing user to post a new shout.
 * TODO: deal with nag screen / not logged in exceptions properly
 *
 */
public class PostShoutScreen extends Activity implements OnClickListener {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.postshoutscreen);

		findViewById(R.id.postshout).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		EditText et = (EditText) findViewById(R.id.shouttext);
		String text = et.getText().toString();

		HttpClient client = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				"http://thingbox.com/members/update_status");

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("status[text]", text));
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);

		String cookie = prefs.getString("cookie", "");

		/* TODO Deal with session errors properly */
		if( cookie.equals("") )
			throw new RuntimeException();
		
		httppost.setHeader("Cookie", cookie);
		
		/* TODO Run this in a separate thread to avoid stalling the UI
		 * while waiting for HTTP response
		 */
		
		
		/* TODO Parse response and show error message if appropriate, or "finish()"
		 * the activity otherwise.
		 */
		
		//HttpResponse response;
		try {
			//response = 
			client.execute(httppost);
			/*
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(response.getEntity().getContent() )); 
			
			
		    String line;

		    while ((line = reader.readLine()) != null)   {

		      System.out.println (line);
		    }
	    */
			finish();
		
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		
	}
}